#include "PhysicsMgr.h"

namespace ouden {

namespace physics {

CSolid* PhysicsMgr::createSolid(bool isStatic)
{
	
	CSolid* newSolid = new CSolid();
	m_pSolids.push_back( newSolid );
	
	//if (isStatic) {
		
	
}

void PhysicsMgr::destroyAllSolids()
{
	while (m_pSolids.size()) {
		delete m_pSolids.back();
		m_pSolids.pop_back();
	}
}

void PhysicsMgr::doCollisionDetection()
{
	
	//If both entities are bounce
	//If entity is bounce and level
	
	//TODO: Need to do for shapes not solids 
	
	//Loop through dynamic solids
	for (int ds=0;ds<m_pDynamicSolids.size();ds++) {
		
		CSolid* dynamicSolid = m_pDynamicSolids[ds];
		
		//Find all nearby static solids from static solid table
		SolidsSector nearbyStaticSolids = getNearbyStaticSolids( dynamicSolid->getPos() );
		
		//Loop through nearby static solids
		for (int ss=0;ss<nearbyStaticSolids.size();ss++) {
			
			//Collide the dynamic solid with the nearby static solids
			collideDynamicWithStatic(dynamicSolid, nearbyStaticSolids[ss]);
			
		}
		
		//Find all nearby dynamic solids from dynamic solid table
		//Collide with other dynamic solids
		
	}
	
}

void PhysicsMgr::collideDynamicWithStatic(CSolid* dynamicSolid, CSolid* staticSolid)
{
	
	//Check for collision
	//TODO: Work out how solid tells parent entity of collide event
	//Call onCollideWith events for each solid
	//If both solids are bouncy
	//Bounce according to solid properties
	
}

PhysicsMgr::SolidsSector PhysicsMgr::getNearbyStaticSolids(Vector pos)
{
	
	SolidsSector nearbySolids;
	
	int x = int(pos[0] / m_fSectorSize);
	int y = int(pos[1] / m_fSectorSize);
	
	if (x >= 0 && x < m_vSectorCount[0] && y >= 0 && y < m_vSectorCount[1]) { 
		nearbySolids = m_StaticSectorTable[x][y];
	}
	
	return nearbySolids;
	
}

} //namespace physics

} //namespace ouden
